<template>
  <div class="hello">
    <h5>bigFileUpload</h5>
    <input type="file" id="shangchuan">
    <div id="jindu"></div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HelloWorld',
  mounted() {
    const shangchuan = document.getElementById("shangchuan");
    shangchuan.onchange = () => {
      var file = document.getElementById("shangchuan").files[0];
      this.upFile({
        file,
        urlUpload: "/apis/newtrickle/upload_chunks",
        urlMerge: "/apis/newtrickle/merge_chunks",
      },function(res){
        console.log(res)
      })
    }
  },
  methods: {
    upFile(obj, callback) {
      let {file, urlUpload, urlMerge, slicingBig = 1024} = obj
      if (!file) return
      var arrAxios = []
      var slicingSize = 1024 * slicingBig;//------这里可以设置多大内存分成一片现在是1g
      var slicingCount = Math.ceil(file.size / slicingSize); // 分片总数
      var ext = file.name.split('.');
      ext = ext[ext.length - 1]; // 获取文件后缀名
      var random = Math.floor(Math.random() * (100 - 1)) + 1;
      var hash = Date.now() + random + file.lastModified; // 文件 hash 实际应用时，hash需要更加复杂，确保唯一性，可以使用uuid
      //创建数组代理来判断完成多久
      console.log(slicingCount)
      var arr = new Proxy(new Array(slicingCount), {
        set(target, key, value, receiver) {
          var prose = 0;
          target.forEach(item => {
            if (item) {
              prose += item
            }
          })
          callback({name: 'upload', value: (prose / slicingCount).toFixed(2), msg: "上传中"})
          return Reflect.set(target, key, value, receiver);
        },
        get(target, key) {
          return target[key];
        }
      })
      for (let i = 0; i < slicingCount; i++) {
        let start = i * slicingSize,
            end = Math.min(file.size, start + slicingSize);
        const form = new FormData();//通过formdata的方式提交
        form.append('file', file.slice(start, end));
        form.append('name', file.name);
        form.append('total', slicingCount);
        form.append('ext', ext);
        form.append('index', i);
        form.append('size', file.size);
        form.append('hash', hash);
        arrAxios.push(axios.post(urlUpload, form, {
          onUploadProgress: progressEvent => {
            arr[i] = (progressEvent.loaded / progressEvent.total * 100 | 0);
          }
        }));//这改成你的分片请求路径
      }
      axios.all(arrAxios).then(() => {
        const data = {
          name: file.name,
          fileId: "2",
          total: slicingCount,
          ext,
          hash
        };
        axios.post(urlMerge, data, {
          onUploadProgress: progressEvent => {
            let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
            callback({name: 'merge', value: complete, msg: "合并中"})
          }
        }).then((res) => {//这改成你的分片合并请求路径
          callback({name: 'ok', value: res.data, msg: "完成"})
        }).catch((err) => {
          callback({name: 'err', value: err, msg: "失败"})
        })
      })
    }
  }
}
</script>
<style lang="css" scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
